package com.mall.service.impl;

import com.mall.common.constants.Constants;
import com.mall.common.utils.RandomUtil;
import com.mall.common.utils.Security;
import com.mall.common.utils.ServletUtil;
import com.mall.controller.vo.UserVO;
import com.mall.dao.custom.CtUserMapper;
import com.mall.entity.User;
import com.mall.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private CtUserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userMapper.selectByEmail(email);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("此用户不存在 , 请进行注册!");
        }
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        return user;
    }

    @Override
    public User getUserByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    @Override
    public int addUser(User user) {
        user.setCreateBy(Security.getCurrentUserId());
        user.setCreateTime(new Date());
        return userMapper.insert(user);
    }

    @Async("taskExecutor")
    @Override
    public void sendMail(String mail, String key) {
        SimpleMailMessage message = new SimpleMailMessage();
        String verifyCode = RandomUtil.generateVerifyCode(6);
        if (StringUtils.isEmpty(mail)) {
            Integer currentUserId = Security.getCurrentUserId();
            User user = this.getUserById(currentUserId);
            message.setTo(user.getEmail());
        } else {
            message.setTo(mail);
            System.out.println(key);
        }
        redisTemplate.opsForValue().set(key, verifyCode, Constants.REGISTER_MAIL_EXPIRE_TIME, TimeUnit.MINUTES);
        //谁发的，发件人的邮箱，也就是你的邮箱
        message.setFrom(Constants.SEND_EMAIL);
        //邮件标题-自定义
        message.setSubject("你的注册验证码");
        message.setText("验证码:" + verifyCode);
        try {
            mailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
        }
    }

    @Override
    public User getUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public UserVO getUserVoById(Integer currentUserId) {
        User user = userMapper.selectByPrimaryKey(currentUserId);
        UserVO userVO = new UserVO();
        userVO.setUsername(user.getUsername());
        userVO.setUserId(user.getUserId());
        userVO.setEmail(user.getEmail());
        int temp;
        switch (user.getRoleKey()) {
            case Constants.ROLE_ADMIN:
                temp = 0;
                break;
            case Constants.ROLE_COMMON_ADMIN:
                temp = 1;
                break;
            case Constants.ROLE_USER:
                temp = 2;
                break;
            default:
                temp = -1;
                break;
        }
        userVO.setRoleKey(temp + "");
        if (StringUtils.isEmpty(user.getAvatar())) {
            userVO.setAvatar(Constants.DEFAULT_AVATAR);
        } else {
            userVO.setAvatar(user.getAvatar());
        }

        return userVO;
    }

    @Override
    public int modifyUserInfo(User user) {
        //todo 当管理员进行修改时 , 应该传UserId .   当本人修改个人信息时 , 不用传UserId
        if (ObjectUtils.isEmpty(user.getUserId())) {
            user.setUserId(Security.getCurrentUserId());
        }
        user.setUpdateBy(Security.getCurrentUserId());
        user.setUpdateTime(new Date());
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public boolean verifyMail(String mail, HttpServletRequest request) {
        User user = userMapper.selectByEmail(mail);
        return !ObjectUtils.isEmpty(user);
    }

    @Override
    public int modifyUserPasswordByMail(String mail, String password) {
        return userMapper.updatePasswordByMail(mail, password);
    }
}
